package com.tnl.app.controller;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tnl.base.Const;
import com.tnl.base.web.JsonController;

@Controller
@RequestMapping("/msg")
public class MsgController extends JsonController {

	private static final Logger logger = LoggerFactory
			.getLogger(MsgController.class);

	 @RequestMapping(value = "/WebChatMainService")
	  public void checkSignature(HttpServletResponse response,HttpServletRequest req) {
		 String signature = req.getParameter("signature");  
	        String timestamp = req.getParameter("timestamp");  
	        String nonce = req.getParameter("nonce");  
	        String echostr = req.getParameter("echostr");  
	        try {
				if (checkSigature(signature, timestamp, nonce)){  
					response.getWriter().print(echostr);  
				}else {  
					response.getWriter().print("validation failed. Bye");  
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
	  }


    public boolean checkSigature(String signature,String timestamp,String nonce){  
        //Define token  
        String token = Const.TOKEN;  
          
        //Sort array  
        String[] tmparr = {token,timestamp,nonce};  
        try {  
            Arrays.sort(tmparr);  
        } catch (NullPointerException e){  
            return false;  
        }  
          
        //implode array  
        StringBuilder builder = new StringBuilder();  
        for (int i=0;i<tmparr.length;i++){  
            builder.append(tmparr[i]);  
        }  
        String raw = builder.toString();  
          
        //SHA-1  
        MessageDigest md = null;  
        byte[] b = null;  
        try {  
            md = MessageDigest.getInstance("SHA-1");  
            b = md.digest(raw.getBytes("UTF-8"));  
        }  
        catch(Exception e) {  
            e.printStackTrace();  
        }   
          
        //Turn sha-1 result to HexString  
        String result = "";  
        for (int i=0; i < b.length; i++) {  
            result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );  
        }  
          
        //Compare and return  
        if (result.equals(signature)){  
            return true;  
        }else{  
            return false;  
        }         
    }  
    

}
